const Router = require("koa-router");
const users = new Router();
const bodyParser = require("koa-bodyparser");
const article = require("../utils/sql");
const fs = require("fs");
const path = require("path");

users.use(bodyParser());

// 注册用户
users.post("/reg", async (ctx) => {
  const params = ctx.request.body;
  const { username, nickname, password } = params;
  // 创建用户文件夹
  const userPath = path.join(__dirname, `../uploads/${username}`);
  fs.mkdir(userPath, (err) => {
    if (err) {
      console.log(err);
    } else {
      console.log("创建用户文件夹成功");
    }
  });

  let data = await article.register(username, nickname, password);
  ctx.body = {
    code: 200,
    msg: "注册成功",
    data,
  };
});

// 登录
users.post("/login", async (ctx) => {
  const params = ctx.request.body;
  const { username, password } = params;
  console.log(username, password);
  let data = await article.login(username, password);
  console.log(data);
  ctx.body = {
    code: 200,
    msg: "登录成功",
    data,
  };
});

// 删除注销用户
users.post("/deleteUser", async (ctx, next) => {
  const { id } = ctx.request.body;
  const data = await article.deleteUser(id);
  ctx.body = {
    code: 200,
    msg: "删除成功",
    data,
  };
});

// 获取单个用户
users.post("/getUser", async (ctx, next) => {
  const { id } = ctx.request.body;
  const data = await article.getUser(id);
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data,
  };
});

// 修改用户信息密码
users.post("/updateUser", async (ctx, next) => {
  const { id, nickname, newPassword } = ctx.request.body;
  console.log(id, nickname, newPassword);
  const data = await article.updateUser(id, nickname, newPassword);
  ctx.body = {
    code: 200,
    msg: "修改成功",
    data,
  };
});

module.exports = users;
